import { createRouter, createWebHistory } from 'vue-router'
import LoginPage from '../views/LoginPage.vue'
import UserManagement from '../views/UserManagement.vue'
import RoleManagement from '../views/RoleManagement.vue'
import PermissionManagement from '../views/PermissionManagement.vue'
import { useUserStore } from '../stores/userStore'

const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginPage,
      meta: { requiresAuth: false }
    },
    {
      path: '/users',
      name: 'users',
      component: UserManagement,
      meta: { requiresAuth: true }
    },
    {
      path: '/roles',
      name: 'roles',
      component: RoleManagement,
      meta: { requiresAuth: true }
    },
    {
      path: '/permissions',
      name: 'permissions',
      component: PermissionManagement,
      meta: { requiresAuth: true }
    },
    {
      path: '/',
      redirect: '/users'
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 检查认证状态
  if (localStorage.getItem('token') && !userStore.isAuthenticated) {
    await userStore.checkAuth()
  }
  
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && userStore.isAuthenticated) {
    next('/users')
  } else {
    next()
  }
})

export default router
